package com.jcli.novel_t;


/**

 1.读取一个txt文档中的所有数据，按照properties中的键值对去匹配，数据与键想同则将其替换为值。
 全部处理完成后输出到一个新txt文档中，完全替换其中的数据。再输出到一个新txt文档中，保留原有的数据。.
 -只做一个替换功能，读取文本 原始数据，按照properties文件进行替换，替换完成后输出到另一个文本，保留另一个文本原有的数据。
 2.输出三个文本，其中的区别。
 3.实现output_replaced.txt的文件名：只读取第一行文本（首行），找到第二个空格前的数据，并将其用作文件名
 */


import java.io.*;
import java.util.*;
import java.util.regex.Pattern;


public class TextFileProcessor02 {
    private Properties properties;

    public TextFileProcessor02(Properties properties) {
        this.properties = properties;
    }

    public void processTextFile(String inputFilePath, String outputFilePath1, String outputFilePath2, String outputFilePath3) {
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter writer1 = new BufferedWriter(new FileWriter(outputFilePath1));
             BufferedWriter writer2 = new BufferedWriter(new FileWriter(outputFilePath2));
             BufferedWriter writer3 = new BufferedWriter(new FileWriter(outputFilePath3, true))) {

            String line;
            while ((line = reader.readLine()) != null) {
                String processedLine = processLine(line);
                writer1.write(processedLine);
                writer1.newLine();

                writer2.write(line);
                writer2.newLine();

                writer3.write(processedLine);
                writer3.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String processLine(String line) {
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            String escapedKey = Pattern.quote(key);

            // 检查行是否包含键，如果包含则进行替换
            if (line.contains(key)) {
                line = line.replaceAll(escapedKey, value);
            }
        }
        return line;
    }

    public static void main(String[] args) {
        Properties properties = new Properties();
        try (InputStream inputStream = new FileInputStream("src/main/resources/config.properties")) {
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        TextFileProcessor02 processor = new TextFileProcessor02(properties);
        processor.processTextFile("input.txt",
                "output_replaced.txt", "output_original.txt",
                "output_combined.txt");
    }
}


    //    输出替换，输出原版，输出叠加

